package com.wwwarehouse.taskcenter.fragment.job_point.step4;

import android.app.Dialog;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.alibaba.fastjson.JSON;
import com.wwwarehouse.common.activity.base.BaseFragment;
import com.wwwarehouse.common.bean.response.CommonClass;
import com.wwwarehouse.common.custom_widget.CircleImageView;
import com.wwwarehouse.common.custom_widget.ElasticScrollView;
import com.wwwarehouse.common.custom_widget.button.StateButton;
import com.wwwarehouse.common.eventbus_event.BluetoothScanResultEvent;
import com.wwwarehouse.common.eventbus_event.ConnectSuccessEvent;
import com.wwwarehouse.common.http.NoHttpUtils;
import com.wwwarehouse.common.tools.DialogTools;
import com.wwwarehouse.common.tools.LogUtils;
import com.wwwarehouse.common.tools.ToastUtils;
import com.wwwarehouse.taskcenter.R;
import com.wwwarehouse.taskcenter.bean.job_point.AddJobPointStep4GetchildScanResponseBean;
import com.wwwarehouse.taskcenter.bean.job_point.AddJobPointStep4LookmessResponseBean;
import com.wwwarehouse.taskcenter.constant.TaskCenterConstant;
import com.wwwarehouse.taskcenter.eventbus_event.TaskPointCardEvent;
import com.wwwarehouse.taskcenter.fragment.bluetooth.BluetoothFragment;

import java.util.ArrayList;
import java.util.HashMap;
import java.util.Map;

import de.greenrobot.event.EventBus;

/**
 * @创建者 chenchao.
 * @创建时间 2017/10/25 20:08
 * @描述 ${TODO}
 */

public class ChooseConnectBluetoothFragment extends BaseFragment implements View.OnClickListener {

    private View mView;
    private ImageView mTaskAddpointStep4Noconnectimg;
    private TextView mTaskAddpointStep4OpenbluetoothTxt;
    private CircleImageView mTaskAddpointStep4Mainimg;
    private TextView mTaskAddpointStep4RelateTxt;
    private ImageView mChooceImg1;
    private View mChooceLineView;
    private ImageView mChooceImg2;
    private LinearLayout mTaskAddpointStep4LineLin;
    private TextView mTaskAddpointStep4Detail1txt;
    private StateButton mTaskAddpointStep4LookdetailStatebtn;
    private StateButton mBtSure;
    private ElasticScrollView mEsvElastic;
    private StateButton detailStateBtn;
       private LinearLayout mainBgLin;
    private TextView mainTitleTxt,mainNumberTxt;

    private static final int REQUEST_SCANCODE_GETMES = 10001, REQUEST_SCANCODE_CHANGE = 10002 , REQUEST_SCANCODE_UNBINDING = 10003,REQUEST_SCANCODE_SAVESTEP= 10004,REQUEST_ALL_ITEM = 10006;
    private String jobPointUkid;
    private String itemCode;
    private String buId;
    private Object productItemUkid, itemName;
    private boolean isBluetoothConnect = false;
    private int total = 0;
    private ArrayList<AddJobPointStep4LookmessResponseBean.ListBean> itemAllList = new ArrayList<>();

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        mView = inflater.inflate(R.layout.fragment_choose_connect_biuetooth, container, false);
        initView(mView);
        return mView;
    }

    @Override
    public void setTitle() {
        if (peekFragment() instanceof ChooseConnectBluetoothFragment) {
            mActivity.setTitle("" + getString(R.string.new_task_step6_add));
        }
    }

    @Override
    public void requestDatas() {
        getAllItem();
    }

    private void initView(View mView) {
        EventBus.getDefault().register(this);

        mTaskAddpointStep4Noconnectimg = (ImageView) mView.findViewById(R.id.task_addpoint_step4_noconnectimg);
        mTaskAddpointStep4OpenbluetoothTxt = (TextView) mView.findViewById(R.id.task_addpoint_step4_openbluetooth_txt);
        mTaskAddpointStep4Mainimg = (CircleImageView) mView.findViewById(R.id.task_addpoint_step4_mainimg);
        mTaskAddpointStep4RelateTxt = (TextView) mView.findViewById(R.id.task_addpoint_step4_relate_txt);
        mChooceImg1 = (ImageView) mView.findViewById(R.id.chooce_img_1);
        mChooceLineView = (View) mView.findViewById(R.id.chooce_line_view);
        mChooceImg2 = (ImageView) mView.findViewById(R.id.chooce_img_2);
        mTaskAddpointStep4LineLin = (LinearLayout) mView.findViewById(R.id.task_addpoint_step4_line_lin);
        mTaskAddpointStep4Detail1txt = (TextView) mView.findViewById(R.id.task_addpoint_step4_detail_1txt);
        mTaskAddpointStep4LookdetailStatebtn = (StateButton) mView.findViewById(R.id.task_addpoint_step4_lookdetail_statebtn);
        mBtSure = (StateButton) mView.findViewById(R.id.bt_sure);
        mEsvElastic = (ElasticScrollView) mView.findViewById(R.id.esv_elastic);
        detailStateBtn = (StateButton) mView.findViewById(R.id.task_addpoint_step4_detail_statebtn);
        mainBgLin = (LinearLayout)mView.findViewById(R.id.task_addpoint_step4_mainimg_bg_rel);
        mainTitleTxt = (TextView)mView.findViewById(R.id.task_addpoint_step4_mainimg_bg_title);
        mainNumberTxt = (TextView)mView.findViewById(R.id.task_addpoint_step4_mainimg_bg_number);



        mTaskAddpointStep4LookdetailStatebtn.setOnClickListener(this);
        mBtSure.setOnClickListener(this);


        mTaskAddpointStep4RelateTxt.setText(getString(R.string.new_task_step4_nobluetooth_txt));
        mBtSure.setVisibility(View.GONE);
        mTaskAddpointStep4Detail1txt.setVisibility(View.VISIBLE);
        detailStateBtn.setVisibility(View.VISIBLE);
        mTaskAddpointStep4Detail1txt.setText(getString(R.string.new_task_step4_gotoconnect_bluetooth_txt));

        detailStateBtn.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if(isBluetoothConnect){
                    pushFragment(new ChooseConnectBluetoothDisconnectFragment());
                }else{
                    pushFragment(new BluetoothFragment());
                }
            }
        });

        jobPointUkid = getArguments().getString("jobPointUkid");
        buId = getArguments().getString("buId");

//        EventBus.getDefault().post(new ConnectSuccessGetnameServiceEvent(""));

    }

    @Override
    public void onClick(View v) {
        int i = v.getId();
        if (i == R.id.task_addpoint_step4_lookdetail_statebtn) {
            Bundle bundle = new Bundle();
            bundle.putString("jobPointUkid",jobPointUkid);
            ChooseJobUnitLookmesspagerFragment4 fragment4 = new ChooseJobUnitLookmesspagerFragment4();
            fragment4.setArguments(bundle);
            pushFragment(fragment4);
        } else if (i == R.id.bt_sure) {
            saveStep();
        }
    }

    public void onEventMainThread(Object event) {
        if (event != null && event instanceof ConnectSuccessEvent) {//蓝牙链接成功
            ConnectSuccessEvent connectSuccessEvent = (ConnectSuccessEvent) event;
            isBluetoothConnect = true;
            mTaskAddpointStep4Detail1txt.setText(R.string.new_task_step4_usebluetooth_tostart_txt);
            mTaskAddpointStep4RelateTxt.setText("已连接蓝牙指环" + connectSuccessEvent.getDeviceName());


        }

        if (event != null && event instanceof BluetoothScanResultEvent) {
            BluetoothScanResultEvent event1 = (BluetoothScanResultEvent)event;
            itemCode = event1.getMsg();
            LogUtils.showErrLog("扫描结果：   " + event1.getMsg());
            scanCodeGetResult();
        }

//        if(event !=null && event instanceof DisconnectScanEvent){
//            isBluetoothConnect = true;
//        }


//        if(event !=null && event instanceof ConnectSuccessGetnameEvent){
//            ConnectSuccessGetnameEvent eventSuccess = (ConnectSuccessGetnameEvent) event;
//            if(!StringUtils.isNullString(eventSuccess.getMsg())){
//                isBluetoothConnect = true;
//                mTaskAddpointStep4Detail1txt.setText(R.string.new_task_step4_usebluetooth_tostart_txt);
//                mTaskAddpointStep4RelateTxt.setText("已连接蓝牙指环" + eventSuccess.getMsg());
//            }
//        }
    }

    @Override
    public void onDestroy() {
        super.onDestroy();
        EventBus.getDefault().unregister(this);
    }

    /**
     * 扫码之后返回的数据
     */
    public void scanCodeGetResult(){
        /**
         * buId	业务单位ID	number	@mock=10000001
         itemCode	实物条码	string	@mock=QC123456789
         jobPointUkid	作业点ukid	number	@mock=100000110
         */
        Map<String,String> map = new HashMap<>();
        map.put("buId","" + buId);
        map.put("itemCode","" + itemCode.replaceAll("\r|\n", ""));
        map.put("jobPointUkid","" + jobPointUkid);

        NoHttpUtils.httpPost(TaskCenterConstant.URL_ADD_JOBPOINT_STEP4_SCANCODE_GETITEM,map,myOnresponse,REQUEST_SCANCODE_GETMES);
        showProgressDialog();
    }

    /**
     * 码被占用，替换
     */
    public void changeCode(){
        /**
         * itemName	生产物的名字	string	@mock=物的名字
         jobPointUkid	作业点ukid	number	@mock=100000110
         productItemUkid	生产物的ukid	number	@mock=500000001
         */
        Map<String,Object> map = new HashMap<>();
        map.put("itemName","" + itemName);
        map.put("jobPointUkid", jobPointUkid );
        map.put("productItemUkid", productItemUkid);

        NoHttpUtils.httpPost(TaskCenterConstant.URL_ADD_JOBPOINT_STEP4_REPLACEITEM,map,myOnresponse,REQUEST_SCANCODE_CHANGE);
        showProgressDialog();
    }

    /**
     * 解绑 操作
     */
    public void unbindCode(){
        /**
         * jobPointUkid	作业点ukid	number	@mock=100000110
         productItemUkid	生产物的ukid	number	@mock=500000001
         */
        Map<String,Object> map = new HashMap<>();
        map.put("jobPointUkid", jobPointUkid );
        map.put("productItemUkid", productItemUkid);

        NoHttpUtils.httpPost(TaskCenterConstant.URL_ADD_JOBPOINT_STEP4_RELIVEBINDING,map,myOnresponse,REQUEST_SCANCODE_UNBINDING);
        showProgressDialog();
    }

    /**
     * 保存步骤
     */

    public void saveStep(){
        Map<String,String> map  = new HashMap<>();
        map.put("jobPointUKid",jobPointUkid);
        map.put("step","4");
        NoHttpUtils.httpPost(TaskCenterConstant.URL_JOBPOINT_SAVESTEP,map,myOnresponse,REQUEST_SCANCODE_SAVESTEP);
        showProgressDialog();
    }

    /**
     * 查看关联物
     */
    public void getAllItem(){
        Map<String, Object> map = new HashMap<>();
        map.put("jobPointUkid", jobPointUkid);
        NoHttpUtils.httpPost(TaskCenterConstant.URL_TASKPOINT_BINDINGPRODUCT,map,myOnresponse,REQUEST_ALL_ITEM);
    }

    public void showBtn (){
        if(total > 0){
            mBtSure.setVisibility(View.VISIBLE);
            mTaskAddpointStep4LookdetailStatebtn.setVisibility(View.VISIBLE);
            mTaskAddpointStep4Detail1txt.setVisibility(View.GONE);
            detailStateBtn.setVisibility(View.GONE);
        }else{
            mBtSure.setVisibility(View.GONE);
            mTaskAddpointStep4LookdetailStatebtn.setVisibility(View.VISIBLE);
            mTaskAddpointStep4Detail1txt.setVisibility(View.GONE);
            detailStateBtn.setVisibility(View.GONE);
        }
    }


    NoHttpUtils.OnResponseListener myOnresponse = new NoHttpUtils.OnResponseListener() {
        @Override
        public void onSucceed(CommonClass commonClass, int i) {

            if(i== REQUEST_SCANCODE_GETMES){
                if("0".equals(commonClass.getCode())){
                    final AddJobPointStep4GetchildScanResponseBean bean = JSON.parseObject(commonClass.getData().toString(),AddJobPointStep4GetchildScanResponseBean.class);
                    /**已绑定 0:成功， 1：已绑定在其他作业点上，是否替换，2 是否解绑*/
                    if("0".equals(bean.getBinding())){
                        total ++ ;
                        showBtn();
                        mainBgLin.setVisibility(View.VISIBLE);
                        mTaskAddpointStep4Detail1txt.setVisibility(View.GONE);
                        mainTitleTxt.setText(bean.getProductItemName());
                        mainNumberTxt.setText("+1");
                        detailStateBtn.setVisibility(View.GONE);
                        mBtSure.setVisibility(View.VISIBLE);
                        mTaskAddpointStep4RelateTxt.setText("已关联生产物("+ total +")");
                    }else if("1".equals(bean.getBinding())){
                        DialogTools.getInstance().showCustomDialogPrompt(mActivity, "提示", "该生产物已被其他作业点添加，是否需要替换它添加到此作业点？", false, new DialogTools.ConfirmListener() {
                            @Override
                            public void setConfirmListener(Dialog dialog, View view, String s) {
                                //确定
                                itemName = bean.getProductItemName();
                                productItemUkid = bean.getProductItemUkid();
                                changeCode();
                                dialog.dismiss();
                            }
                        }, "替换", "取消");

                    }else if("2".equals(bean.getBinding())){
                        DialogTools.getInstance().showCustomDialogPrompt(mActivity, "提示", "是否需要解绑这次扫描的生产物？", false, new DialogTools.ConfirmListener() {
                            @Override
                            public void setConfirmListener(Dialog dialog, View view, String s) {
                                //确定
                                productItemUkid = bean.getProductItemUkid();
                                unbindCode();
                                dialog.dismiss();
                            }
                        }, "解绑", "取消");

                    }
                }else{
                    ToastUtils.showToast("" + commonClass.getMsg());
                }
                //替换链接
            }else if(i == REQUEST_SCANCODE_CHANGE){
                if("0".equals(commonClass.getCode())){
                    total ++ ;
                    mainBgLin.setVisibility(View.VISIBLE);
                    mainTitleTxt.setText(itemName+"");
                    mainNumberTxt.setText("+1");
                    showBtn();
                    mTaskAddpointStep4RelateTxt.setText("已关联生产物("+ total +")");
                }else{
                    ToastUtils.showToast("" + commonClass.getMsg());
                }
                //解绑操作
            }else if(i == REQUEST_SCANCODE_UNBINDING){
                if("0".equals(commonClass.getCode())){
                    mainNumberTxt.setText("-1");
                    if(total > 0 ){
                        total--;
                    }
                    showBtn();
                    mTaskAddpointStep4RelateTxt.setText("已关联生产物("+ total +")");
                }else{
                    ToastUtils.showToast("" + commonClass.getMsg());
                }
                //完成此步
            }else if(i == REQUEST_SCANCODE_SAVESTEP){
                if("0".equals(commonClass.getCode())){
                    TaskPointCardEvent event = new TaskPointCardEvent();
                    event.setFinish4(true);

                    EventBus.getDefault().post(event);
                    popFragment();
                }else{
                    ToastUtils.showToast("" + commonClass.getMsg());
                }
            }else if(i == REQUEST_ALL_ITEM){
                itemAllList = (ArrayList<AddJobPointStep4LookmessResponseBean.ListBean>) JSON.parseArray(commonClass.getData().toString(),AddJobPointStep4LookmessResponseBean.ListBean.class);
                for(AddJobPointStep4LookmessResponseBean.ListBean bean : itemAllList){
                    try {
                        total += Integer.parseInt(bean.getNum());
                    } catch (Exception e) {
                        e.printStackTrace();
                    }

                }
            }

        }
        @Override
        public void onFailed(String s, int i) {
        }
        @Override
        public void onFinish(int i) {
            dismissProgressDialog();
        }
    };
}
